/**
 * 
 */
package com.mzba.place.ui;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.gson.Gson;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.ReportDetailAdapter;
import com.mzba.place.entity.CommentsEntity;
import com.mzba.place.entity.ReportDetailEntity;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportUserEntity;
import com.mzba.place.ui.widget.CustomListView;
import com.mzba.place.utils.AccessTokenKeeper;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageLoader;
import com.mzba.place.utils.ScreenShot;
import com.mzba.place.utils.ShareUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.tencent.open.HttpStatusException;
import com.tencent.open.NetworkUnavailableException;
import com.tencent.tauth.Constants;
import com.tencent.tauth.IRequestListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.weibo.sdk.android.api.WeiboAPI;
import com.tencent.weibo.sdk.android.component.Authorize;
import com.tencent.weibo.sdk.android.component.sso.AuthHelper;
import com.tencent.weibo.sdk.android.component.sso.OnAuthListener;
import com.tencent.weibo.sdk.android.component.sso.WeiboToken;
import com.tencent.weibo.sdk.android.model.AccountModel;
import com.tencent.weibo.sdk.android.model.BaseVO;
import com.tencent.weibo.sdk.android.model.ModelResult;
import com.tencent.weibo.sdk.android.network.HttpCallback;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

/**
 * report 详情
 * 
 * @author Iris
 * 
 */
@SuppressLint("ShowToast") 
public class ReportDetailActivity extends BasicActivity implements Callback,
		BasicUIEvent, OnClickListener,HttpCallback {

	private CustomListView reportDetailListView;
	private ReportEntity reportEntity;
	private ReportDetailEntity reportDetailEntity;
	private TextView tv_reportType;
	private TextView tv_reportTime;
	private ImageView iv_user_icon;
	private TextView tv_user_name;
	private TextView tv_report_content;
	private ImageView iv_reportTypeIcon;
	private ImageView iv_reportImage;
	private TextView tv_comment;
	private ReportDetailAdapter reportDetailAdapter;
	private ImageLoader mImageLoader;
	private ReportUserEntity reportUserEntity;
	private String Url;
	private MapView mMapView;
	private MapController mMapController = null;

	private RelativeLayout rl_image_bg;

	private WeakReference<Bitmap> smallBitmap;
	private WeakReference<Bitmap> reportBitmap;
	private WeakReference<Bitmap> reportMapBitmap;
	private WeakReference<Bitmap> reportIconBitmap;

	private double lon;
	private double lat;

	private final static int TASK_DETAIL = 0X1234;
	private static Handler handler;

	/**
	 * 添加
	 */
	private final int menu_add = 0x1235;
	/**
	 * 赞
	 */
	private final int menu_vote = 0x1236;
	/**
	 * 收藏
	 */
	private final int menu_star = 0x1237;
	/**
	 * 举报
	 */
	private final int menu_inform = 0x1238;

	/**
	 * 评论
	 */
	private final static int menu_comment = 0x1240;

	/**
	 * 下载图片
	 */
	private final static int Task_Load_Image = 0x1241;

	/**
	 * 下载缩略图
	 */
	private final static int Task_Load_Small_Image = 0x1244;

	/**
	 * 下载地图
	 */
	private final static int Task_Load_map = 0x1242;
	/**
	 * 下载用户头像
	 */
	private final static int Task_user_icon = 0x1243;

	/**
	 * 纠错
	 */
	private final static int menu_refine = 0x1245;

	private int rc = 1;

	/**
	 * 评论 举报
	 */
	private ImageButton ib_confrim;
	/**
	 * 显示最低下一栏
	 */
	RelativeLayout rl_view;
	/**
	 * 评论和详情的内容
	 */
	private EditText et_conten;
	ImageView iv_comment_first;

	private PopupWindow popup;
	private int zoom = 18;
	private View actioon_bar;

	private TextView tv_menu_vote, tv_menu_star, tv_menu_inform, tv_menu_share,
			tv_menu_refine;
	private TextView tv_menu_add, tv_menu_comment;
	
	private final static int menu_sina = 5;
//	private final int menu_qq = 6;
	private final int menu_weixin_contact = 7;
	private final int menu_weixin_friend = 8;
	private final int menu_tengxun = 9;
	
	/**
	 * 微信和朋友网
	 */
	private IWXAPI api;
	private Weibo mSinaWeibo;
	private Oauth2AccessToken accessToken;
	/**
	 * qq空间
	 */
	private Tencent mTencent;
	/**
	 * 
	 */
	private WeiboAPI tx_weiboAPI;// 微博相关API
	private StatusesAPI sinaWeiboAPI;
	/**
	 * 分享的url
	 */
	private String share_url;
	/**
	 * 分享的内容
	 */
	String content ;
	/**
	 * 分享的图片
	 */
	Bitmap thumbBmp;
	/**
	 * 新浪微博分享的图片地址
	 */
	String photo_url = AppContext.getSDPath()+"pu.png";
	
	String weibo_name =" @shenbiananquan";
	
	private String[] shareType = new String[]{"qq空间","新浪微博","微信","朋友网","腾讯微博"};

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.activity_report_detail);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		LayoutInflater inflator = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		actioon_bar = inflator.inflate(R.layout.actionbar_detail, null);
		actionBar.setCustomView(actioon_bar);
		setTitle("详细信息");
		mImageLoader = ImageLoader.getInstance(this);
		handler = new Handler(this);
		api = WXAPIFactory.createWXAPI(this, AppContext.WX_APPID, false);
		api.registerApp(AppContext.WX_APPID);
		
		api = WXAPIFactory.createWXAPI(this, AppContext.WX_APPID);
		
		initQQZoom();
		PlaceApplication app = (PlaceApplication) getApplication();
		if (app.mBMapManager == null) {
			app.mBMapManager = new BMapManager(this);
			app.mBMapManager.init(PlaceApplication.strKey,
					new PlaceApplication.MyGeneralListener());
		}
		
		init();
		
		
	}
	
	/**
	 * qq空间注册id
	 */
	private void initQQZoom() {
		mTencent = Tencent.createInstance(UrlConfig.qq_appid,this.getApplicationContext());
	}


	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	private void init() {
		reportDetailListView = (CustomListView) findViewById(R.id.list_report_detail);
		View headerView = getLayoutInflater().inflate(
				R.layout.activity_report_detail_headview, null);
		tv_reportType = (TextView) headerView.findViewById(R.id.tv_report_type);
		tv_reportTime = (TextView) headerView.findViewById(R.id.tv_report_time);
		tv_report_content = (TextView) headerView
				.findViewById(R.id.tv_report_content);
		tv_user_name = (TextView) headerView.findViewById(R.id.tv_user_name);
		iv_user_icon = (ImageView) headerView.findViewById(R.id.iv_user_icon);
		iv_reportTypeIcon = (ImageView) headerView
				.findViewById(R.id.iv_report_type_icon);
		iv_reportImage = (ImageView) headerView
				.findViewById(R.id.iv_report_image);
		rl_image_bg = (RelativeLayout) headerView
				.findViewById(R.id.rl_report_image);
		iv_reportImage.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ReportDetailActivity.this,
						PhotoDetailActivity.class);
				intent.putExtra("small_pic",
						reportDetailEntity.getThumbnail_pic());
				intent.putExtra("big_pic", reportDetailEntity.getOriginal_pic());
				startActivity(intent);
			}
		});
		mMapView = (MapView) headerView.findViewById(R.id.report_bmapView);
		mMapController = mMapView.getController();
		mMapController.enableClick(true);
		mMapController.setZoom(18);
		mMapView.setDoubleClickZooming(false);
		mMapView.setBuiltInZoomControls(true);
//		mMapView.setOnTouchListener(mapTouchListener);
		tv_comment = (TextView) headerView.findViewById(R.id.tv_report_comment);
		reportDetailListView.addHeaderView(headerView);

		iv_comment_first = (ImageView) findViewById(R.id.iv_comment_first);
		rl_view = (RelativeLayout) findViewById(R.id.rl_view);
		et_conten = (EditText) findViewById(R.id.et_content);

		tv_menu_vote = (TextView) findViewById(R.id.tv_menu_vote);
		tv_menu_star = (TextView) findViewById(R.id.tv_menu_star);
		tv_menu_comment = (TextView) actioon_bar.findViewById(R.id.tv_menu_comment);
		tv_menu_inform = (TextView) findViewById(R.id.tv_menu_inform);
		tv_menu_share = (TextView) findViewById(R.id.tv_menu_share);
		tv_menu_refine = (TextView) findViewById(R.id.tv_menu_refine);
		tv_menu_add = (TextView) actioon_bar.findViewById(R.id.tv_menu_add);
		tv_menu_vote.setOnClickListener(this);
		tv_menu_star.setOnClickListener(this);
		tv_menu_inform.setOnClickListener(this);
		tv_menu_share.setOnClickListener(this);
		tv_menu_comment.setOnClickListener(this);
		tv_menu_refine.setOnClickListener(this);
		tv_menu_add.setOnClickListener(this);

		UICore.eventTask(ReportDetailActivity.this, this, TASK_DETAIL, null,
				true);
	}

	private void initDate() {
		reportUserEntity = reportDetailEntity.getUser();
		reportDetailAdapter = new ReportDetailAdapter(this,
				reportDetailEntity.getComments(), mImageLoader);
		lon = reportDetailEntity.getCoordinate().getLon();
		lat = reportDetailEntity.getCoordinate().getLat();

		Url = "http://api.map.baidu.com/staticimage?center=" + lon + "," + lat
				+ "&width=" + CanvasWidth + "&height=300&zoom=" + zoom
				+ "&markers=" + lon + "," + lat + "&markerStyles=l";
		tv_reportType.setText(Utils.getReportType(this)[reportDetailEntity
				.getType_id()] + "");
		iv_reportTypeIcon
				.setBackgroundResource(Utils.getReportTypeIcon()[reportDetailEntity
						.getType_id() - 1]);
		tv_reportTime.setText(Utils.getCreateAt(reportDetailEntity
				.getCreated_at()));
		tv_report_content.setText(reportDetailEntity.getText());
		tv_user_name.setText(reportUserEntity.getScreen_name());
		reportDetailListView.setAdapter(reportDetailAdapter);
		tv_comment.setText(reportDetailEntity.getComments_count() + "");
		if (reportDetailEntity.getComments_count() > 0) {
			tv_menu_comment
					.setText(reportDetailEntity.getComments_count() + "");
			iv_comment_first.setVisibility(View.VISIBLE);
		} else {
			tv_menu_comment.setText("");
			iv_comment_first.setVisibility(View.INVISIBLE);
		}
		// bt_vote.setText(reportDetailEntity.getVotes_count() + "赞");
		if (StringUtil.isBlank(reportUserEntity.getProfile_image_url())) {
			iv_user_icon.setVisibility(View.GONE);
		} else {
			UICore.eventTask(this, this, Task_user_icon, null, false);
		}

		// UICore.eventTask(this, this, Task_Load_map, null, false);

		if (StringUtil.isBlank(reportDetailEntity.getBmiddle_pic())) {
			iv_reportImage.setVisibility(View.GONE);
			rl_image_bg.setVisibility(View.GONE);
		} else {
			UICore.eventTask(this, this, Task_Load_Small_Image, null, false);
		}
	}

	private void send() {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("image/*");
		if (StringUtil.isNotBlank(reportDetailEntity.getBmiddle_pic())) {
			Uri uri = Uri.fromFile(Utils.getImageFile(this,
					reportDetailEntity.getBmiddle_pic()));
			shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		}
		shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享");
		shareIntent.putExtra(Intent.EXTRA_TEXT, reportDetailEntity.getText());
		shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(Intent.createChooser(shareIntent, "分享到"));
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (UICore.getInstance().getPusherService() != null && UICore.getInstance().isMainActivityExist()) {
				finish();
			} else {
				Intent intent = new Intent(this, SplashActivity.class);
				startActivity(intent);
				finish();
			}
		} 
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			if (UICore.getInstance().getPusherService() != null && UICore.getInstance().isMainActivityExist()) {
				finish();
			} else {
				Intent intent = new Intent(this, SplashActivity.class);
				startActivity(intent);
				finish();
			}
			break;
		case menu_add:
			Intent intent = new Intent(this, ReportUploadActivity.class);
			startActivity(intent);
			break;
		// case menu_vote:
		// UICore.eventTask(ReportDetailActivity.this, this, menu_vote, null,
		// true);
		// break;
		// case menu_star:
		// UICore.eventTask(ReportDetailActivity.this, this, menu_star, null,
		// true);
		// break;
		// case menu_inform:
		// showContent(menu_inform);
		// break;
		// case menu_share:
		// send();
		// break;
		case menu_comment:
			showContent(menu_comment);
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case TASK_DETAIL:
				initDate();
				initMenuStatus();
				if (lat != 0.0 && lon != 0.0) {
					try {
						Thread.sleep(500);
						handler.sendEmptyMessage(Task_Load_map);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				break;
			case menu_vote:
				if (rc == 0) {
					onToast(getString(R.string.rc_sc));
				} else {
					onToast(getString(R.string.rc_error));
				}
				initMenuStatus();
				break;
			case menu_star:
				if (rc == 0) {
					onToast(getString(R.string.rc_sc));
				} else {
					onToast(getString(R.string.rc_error));
				}
				initMenuStatus();
				break;
			case menu_inform:
				if (rc == 0) {
					onToast(getString(R.string.rc_sc));
				} else {
					onToast(getString(R.string.rc_error));
				}
				break;
			case menu_comment:
				reportDetailAdapter.notifyDataSetChanged();
				reportDetailEntity.setComments_count(reportDetailEntity.getComments_count() + 1);
				tv_menu_comment.setText(reportDetailEntity.getComments_count() + "");
				iv_comment_first.setVisibility(View.VISIBLE);
				break;
			case Task_Load_Image:
				iv_reportImage.setImageBitmap(reportBitmap.get());
				ScreenShot.savePic(reportBitmap.get(), photo_url);
				break;
			case Task_Load_map:
				GeoPoint gp = new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
				mMapController.animateTo(gp);
				OverlayItem item = new OverlayItem(gp, null, null);
				Drawable drawable = getResources().getDrawable(Utils.getReportTypeIcon()[reportDetailEntity.getType_id() - 1]);
				ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(drawable, mMapView);
				overlay.removeAll();
				overlay.addItem(item);
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(overlay);
				mMapView.refresh();
				mMapController.setScrollGesturesEnabled(false);
				// iv_mapView.setImageBitmap(reportMapBitmap.get());
				break;
			case Task_user_icon:
				iv_user_icon.setImageBitmap(reportIconBitmap.get());
				break;
			case Task_Load_Small_Image:
				if (smallBitmap != null && smallBitmap.get() != null) {
					iv_reportImage.setImageBitmap(smallBitmap.get());
				}
				UICore.eventTask(ReportDetailActivity.this, this,
						Task_Load_Image, null, false);
				break;
			case menu_refine:
				if (rc == 0) {
					onToast(getString(R.string.rc_sc));
				} else {
					onToast(getString(R.string.rc_error));
				}
				break;
			case menu_sina:
				Toast.makeText(ReportDetailActivity.this,"发送成功",Toast.LENGTH_LONG).show();
				break;
			case menu_weixin_contact:
				Toast.makeText(ReportDetailActivity.this,"发送成功",Toast.LENGTH_LONG).show();
				break;
			case menu_weixin_friend:
				Toast.makeText(ReportDetailActivity.this,"发送成功",Toast.LENGTH_LONG).show();
				break;	
			case menu_tengxun:
				Toast.makeText(ReportDetailActivity.this,"发送成功",Toast.LENGTH_LONG).show();
				break;	
				
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			String response;
			HashMap<String, String> map;
			switch (mes) {
			case TASK_DETAIL:
				Intent intent = getIntent();
				reportEntity = (ReportEntity) intent
						.getSerializableExtra("report_detail");
				response = HttpUtils.doGet(allExecute(UrlConfig
						.reportDetail(reportEntity.getId() + "")));
				share_url = allExecute(UrlConfig.reportDetail(reportEntity.getId() + ""));
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					reportDetailEntity = gson.fromJson(response,
							ReportDetailEntity.class);
			
				}
				handler.sendEmptyMessage(TASK_DETAIL);
				break;

			case menu_vote:
				if (reportDetailEntity.isIs_voted()) {// 取消赞
					map = new HashMap<String, String>();
					map.put("auth_token", AppContext.getInstance()
							.getAuthToken());
					response = HttpUtils.doPost(this,
							UrlConfig.un_vote(reportDetailEntity.getId() + ""),
							map);
					rc = getRc(response);
					if (rc == 0) {
						reportDetailEntity.setIs_voted(false);
					}
					handler.sendEmptyMessage(menu_vote);
				} else {
					map = new HashMap<String, String>();
					map.put("auth_token", AppContext.getInstance()
							.getAuthToken());
					response = HttpUtils.doPost(this,
							UrlConfig.vote(reportDetailEntity.getId() + ""),
							map);
					rc = getRc(response);
					if (rc == 0) {
						reportDetailEntity.setIs_voted(true);
					}
					handler.sendEmptyMessage(menu_vote);
				}
				break;
			case menu_star:
				if (reportDetailEntity.isIs_stared()) {
					map = new HashMap<String, String>();
					map.put("auth_token", AppContext.getInstance()
							.getAuthToken());
					response = HttpUtils.doPost(this,
							UrlConfig.un_star(reportDetailEntity.getId() + ""),
							map);
					rc = getRc(response);
					if (rc == 0) {
						reportDetailEntity.setIs_stared(false);
					}
					handler.sendEmptyMessage(menu_star);
				} else {
					map = new HashMap<String, String>();
					map.put("auth_token", AppContext.getInstance()
							.getAuthToken());
					response = HttpUtils.doPost(this,
							UrlConfig.star(reportDetailEntity.getId() + ""),
							map);
					rc = getRc(response);
					if (rc == 0) {
						reportDetailEntity.setIs_stared(true);
					}
					handler.sendEmptyMessage(menu_star);
				}
				break;
			case menu_inform:
				map = new HashMap<String, String>();
				map.put("auth_token", AppContext.getInstance().getAuthToken());
				map.put("reason", et_conten.getText().toString().trim());
				response = HttpUtils.doPost(this,
						UrlConfig.inform(reportDetailEntity.getId() + ""), map);
				rc = getRc(response);
				handler.sendEmptyMessage(menu_star);
				break;
			case menu_comment:
				map = new HashMap<String, String>();
				map.put("auth_token", AppContext.getInstance().getAuthToken());
				map.put("content", et_conten.getText().toString().trim());
				response = HttpUtils.doPost(this,UrlConfig.comment(reportDetailEntity.getId()
										+ ""), map);
				Log.d("debug", "response---==>" + response);
				Gson gson = new Gson();
				CommentsEntity commentsEntity = gson.fromJson(response,
						CommentsEntity.class);
				reportDetailAdapter.commentsList.add(commentsEntity);
				handler.sendEmptyMessage(menu_comment);
				break;
			case Task_Load_Image:
				reportBitmap = new WeakReference<Bitmap>(Utils.getBitmap(this,
						reportDetailEntity.getBmiddle_pic()));
				if (reportBitmap.get() != null) {
					handler.sendEmptyMessage(Task_Load_Image);
				}
				break;

			case Task_Load_Small_Image:
				smallBitmap = new WeakReference<Bitmap>(Utils.getBitmap(this,
						reportDetailEntity.getThumbnail_pic()));
				handler.sendEmptyMessage(Task_Load_Small_Image);
				break;

			case Task_Load_map:
				reportMapBitmap = new WeakReference<Bitmap>(Utils.getBitmap(
						this, Url));
				if (reportMapBitmap != null) {
					handler.sendEmptyMessage(Task_Load_map);
				}

				break;

			case Task_user_icon:
				reportIconBitmap = new WeakReference<Bitmap>(Utils.getBitmap(
						this, reportUserEntity.getProfile_image_url()));
				if (reportIconBitmap.get() != null) {
					handler.sendEmptyMessage(Task_user_icon);
				}

				break;
			case menu_refine:
				map = new HashMap<String, String>();
				map.put("auth_token", AppContext.getInstance().getAuthToken());
				map.put("note", et_conten.getText().toString().trim());
				response = HttpUtils.doPost(this,
						UrlConfig.refine(reportDetailEntity.getId() + ""), map);
				Log.d("debug", "response--menu_refine  -==>" + response);
				rc = getRc(response);
				handler.sendEmptyMessage(menu_refine);
				break;
			case menu_weixin_contact:
				if (smallBitmap!=null) {
					sendReq(share_url, content, smallBitmap.get(), menu_weixin_contact);
				}else {
					sendReq(share_url, content, null, menu_weixin_contact);
				}
				break;
			case menu_weixin_friend:
				if (smallBitmap!=null) {
					sendReq(share_url, content, smallBitmap.get(), menu_weixin_friend);
				}else {
					sendReq(share_url, content, null, menu_weixin_friend);
				}
				break;
			case menu_sina:
				accessToken = AccessTokenKeeper.readAccessToken(ReportDetailActivity.this);
				if (accessToken.isSessionValid()) {
					if (sinaWeiboAPI==null) {
						sinaWeiboAPI = new StatusesAPI(accessToken);
					}
					
					if (StringUtil.isBlank(reportDetailEntity.getBmiddle_pic())) {
						sinaWeiboAPI.update(content, lat+"", lon+"", ShareUtils.sinaRequestListener);
					}else{
					sinaWeiboAPI.upload(content, photo_url, lat+"", lon+"", ShareUtils.sinaRequestListener);
					}
				}
				break;
			case menu_tengxun:
				tx_weiboAPI.addPicUrl(this, content+weibo_name, "json", lon,lat, reportDetailEntity.getBmiddle_pic(), 0, 0, this, null,BaseVO.TYPE_JSON);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.execute(mes, obj);
	}

	private String allExecute(String url) {
		StringBuilder builder = new StringBuilder();
		builder.append(url);
		builder.append("?auth_token=");
		builder.append(AppContext.getInstance().getAuthToken());
		builder.append("&from=android_app");
		return builder.toString();
	}

	private int getRc(String json) {
		JSONObject jsonObject;
		int rc = 1;
		try {
			jsonObject = new JSONObject(json);
			rc = jsonObject.getInt("rc");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return rc;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.actionbarsherlock.app.SherlockFragmentActivity#onCreateOptionsMenu
	 * (com.actionbarsherlock.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	private void initMenuStatus() {
		if (reportDetailEntity != null && reportDetailEntity.isIs_voted()) {
			tv_menu_vote.setCompoundDrawablesWithIntrinsicBounds(null,
					getResources().getDrawable(R.drawable.icon_unvote), null,
					null);
			tv_menu_vote.setText(getString(R.string.menu_cancel_vote));
		} else {
			tv_menu_vote.setCompoundDrawablesWithIntrinsicBounds(null,
					getResources().getDrawable(R.drawable.icon_vote), null,
					null);
			tv_menu_vote.setText(getString(R.string.menu_vote));
		}
		if (reportDetailEntity != null && reportDetailEntity.isIs_stared()) {
			tv_menu_star.setCompoundDrawablesWithIntrinsicBounds(null,
					getResources().getDrawable(R.drawable.icon_unstar), null,
					null);
			tv_menu_star.setText(getString(R.string.menu_cancel_stas));
		} else {
			tv_menu_star.setCompoundDrawablesWithIntrinsicBounds(null,
					getResources().getDrawable(R.drawable.icon_star), null,
					null);
			tv_menu_star.setText(getString(R.string.menu_stas));
		}
	}

	@SuppressWarnings("deprecation")
	private void showContent(final int tag) {
		if (popup == null) {
			LayoutInflater mLayoutInflater = (LayoutInflater) this
					.getSystemService(LAYOUT_INFLATER_SERVICE);
			View comment_inform = mLayoutInflater.inflate(
					R.layout.pop_comment_inform, null);
			ib_confrim = (ImageButton) comment_inform
					.findViewById(R.id.bt_confirm);
			et_conten = (EditText) comment_inform.findViewById(R.id.et_content);
			popup = new PopupWindow(comment_inform, LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);

		}
		et_conten.setText("");
		if (tag == menu_comment) {
			et_conten.setHint(getString(R.string.hint_comment));
		} else if (tag == menu_inform) {
			et_conten.setHint(getString(R.string.hint_inform));
		} else if (tag == menu_refine) {
			et_conten.setHint(getString(R.string.hint_refine));
		}
		// 使其聚集
		popup.setFocusable(true);
		// 设置允许在外点击消失
		popup.setOutsideTouchable(true);

		// 弹出软件盘,adust 不档文本档
		popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
		popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.showAtLocation(findViewById(R.id.iv_comment_first),
				Gravity.CLIP_HORIZONTAL | Gravity.BOTTOM, 0, 0);

		popup.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {

			}
		});
		ib_confrim.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (tag == menu_comment) {
					if (et_conten.getText().toString().trim().equals("")) {
						Toast.makeText(ReportDetailActivity.this, "请输入评论内容！",
								Toast.LENGTH_LONG).show();
						return;
					}
					UICore.eventTask(ReportDetailActivity.this,
							ReportDetailActivity.this, menu_comment, null, true);
				} else if (tag == menu_inform) {
					if (et_conten.getText().toString().trim().equals("")) {
						Toast.makeText(ReportDetailActivity.this, "请输入举报内容！",
								Toast.LENGTH_LONG).show();
						return;
					}
					UICore.eventTask(ReportDetailActivity.this,
							ReportDetailActivity.this, menu_inform, null, true);
				} else if (tag == menu_refine) {
					if (et_conten.getText().toString().trim().equals("")) {
						Toast.makeText(ReportDetailActivity.this, "请输入纠错内容！",
								Toast.LENGTH_LONG).show();
						return;
					}
					UICore.eventTask(ReportDetailActivity.this,
							ReportDetailActivity.this, menu_refine, null, true);
				}

				popup.dismiss();
			}
		});
	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		if (smallBitmap != null && smallBitmap.get() != null
				&& !smallBitmap.get().isRecycled()) {
			smallBitmap.get().recycle();
			smallBitmap = null;
		}
		if (reportBitmap != null && reportBitmap.get() != null
				&& !reportBitmap.get().isRecycled()) {
			reportBitmap.get().recycle();
			reportBitmap = null;
		}
		if (reportMapBitmap != null && reportMapBitmap.get() != null
				&& !reportMapBitmap.get().isRecycled()) {
			reportMapBitmap.get().recycle();
			reportMapBitmap = null;
		}
		if (reportIconBitmap != null && reportIconBitmap.get() != null
				&& !reportIconBitmap.get().isRecycled()) {
			reportIconBitmap.get().recycle();
			reportIconBitmap = null;
		}
		System.gc();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		if (reportDetailEntity == null) {
			return;
		}
		switch (v.getId()) {
		case R.id.tv_menu_vote:
			UICore.eventTask(ReportDetailActivity.this, this, menu_vote, null, true);
			break;
		case R.id.tv_menu_star:
			UICore.eventTask(ReportDetailActivity.this, this, menu_star, null, true);
			break;

		case R.id.tv_menu_inform:
			showContent(menu_inform);
			break;

		case R.id.tv_menu_share:
			send();
			content =  reportDetailEntity.getText();			
//			ShareUtils.setHandle(handler, menu_sina);
//			chooseAction("转发到",shareType, R.id.tv_menu_share);
			break;

		case R.id.tv_menu_comment:
			showContent(menu_comment);
			break;
		case R.id.tv_menu_refine:
			showContent(menu_refine);
			break;
		case R.id.tv_menu_add:
			Intent intent = new Intent(this, ReportUploadActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}

	}



	/* (non-Javadoc)
	 * @see com.mzba.place.BasicActivity#doSelectChooseEvent(int, int)
	 */
	@Override
	public void doSelectChooseEvent(int which, int chooseType) {
		super.doSelectChooseEvent(which, chooseType);
		if (chooseType==R.id.tv_menu_share) {
			switch (which) {
			case 0:
				//QQ
				onQQLogin();	
				break;
			case 1:
				//新浪
				sinaAccessToken();
				break;
			case 2:
				//微信
				shareWX(menu_weixin_contact);
				break;
			case 3:
				//朋友网
				shareWX(menu_weixin_friend);
				break;
			case 4:
				//腾讯微博
				TXWBAccessToken();
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 分享到微信
	 * 
	 * @param type
	 */
	private void shareWX(int type) {
		if (type == menu_weixin_contact) {
			UICore.eventTask(this, this, menu_weixin_contact, null, true);
		} else {
			UICore.eventTask(this, this, menu_weixin_friend, null, true);
		}

	}


	/**
	 * 
	 * 微信分享
	 * @param urls
	 * @param text
	 * @param bmp
	 * @param type
	 */
	public void sendReq(String urls, String text, Bitmap bmp, int type) {

		String url = urls;// 收到分享的好友点击信息会跳转到这个地址去
		WXWebpageObject localWXWebpageObject = new WXWebpageObject();
		localWXWebpageObject.webpageUrl = url;
		WXMediaMessage localWXMediaMessage = new WXMediaMessage(
				localWXWebpageObject);
		localWXMediaMessage.title = tv_reportType.getText().toString();// 不能太长，否则微信会提示出错。不过博主没验证过具体能输入多长。
		localWXMediaMessage.description = text;
		if (bmp!=null) {
			localWXMediaMessage.thumbData = Utils.bmpToByteArray(bmp, true);
		}
		SendMessageToWX.Req localReq = new SendMessageToWX.Req();
		localReq.transaction = System.currentTimeMillis() + "";
		localReq.message = localWXMediaMessage;
		if (type == menu_weixin_friend) {
			localReq.scene = SendMessageToWX.Req.WXSceneTimeline;
		} else {
			localReq.scene = SendMessageToWX.Req.WXSceneSession;
		}

		api.sendReq(localReq);
	}
   
	/**
	 * 新浪授权
	 */
	private void sinaAccessToken() {
		accessToken = AccessTokenKeeper.readAccessToken(this);
		content = content  + " @身边安全调查员";
		if (accessToken.isSessionValid()) {
			UICore.eventTask(this, this, menu_sina, null, true);
		} else {
			mSinaWeibo = Weibo.getInstance(UrlConfig.sina_appkey,
					UrlConfig.redirect_url);
			mSinaWeibo.authorize(this, new SinaOAuthListener());
		}
	}
	/**
	 * 新浪微博授权
	 * 
	 * @author iris
	 *
	 */
		class SinaOAuthListener implements WeiboAuthListener {

			@Override
			public void onCancel() {
				
			}

			@Override
			public void onComplete(Bundle values) {
				String token = values.getString("access_token");
	            String expires_in = values.getString("expires_in");
				final Oauth2AccessToken accessToken = new Oauth2AccessToken(token, expires_in);
				if (accessToken.isSessionValid()) {
					String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(accessToken.getExpiresTime()));
					System.out.println("+++++++++++++++" + "认证成功：token" + token + ";有效期：" + date);

					
									AccountAPI accountApi = new AccountAPI(accessToken);
					accountApi.getUid(new RequestListener() {
						
						@Override
						public void onIOException(IOException arg0) {
							System.out.println("---------------------" + arg0.getMessage());
						}
						
						@Override
						public void onError(WeiboException arg0) {
							System.out.println("-------------------------------------------------" + arg0.getMessage());
						}
						
						@Override
						public void onComplete(String arg0) {
							try {
								if (StringUtil.isNotBlank(arg0)) {
									JSONObject obj = new JSONObject(arg0);
									UsersAPI userApi = new UsersAPI(accessToken);
									userApi.show(Long.parseLong(obj.getString("uid")), new RequestListener() {
										
										@Override
										public void onIOException(IOException arg0) {
											System.out.println("---------------------" + arg0.getMessage());
										}
										
										@Override
										public void onError(WeiboException arg0) {
											System.out.println("---------------------" + arg0.getMessage());
										}
										
										@Override
										public void onComplete(String arg0) {
											if (StringUtil.isNotBlank(arg0)) {
												try {
													@SuppressWarnings("unused")
													JSONObject resultObj = new JSONObject(arg0);
													handler.post(new Runnable() {
														
														@Override
														public void run() {
															AccessTokenKeeper.keepAccessToken(ReportDetailActivity.this, accessToken);
															UICore.eventTask(ReportDetailActivity.this, ReportDetailActivity.this, menu_sina, null, true);
														}
													});
												} catch (JSONException e) {
													e.printStackTrace();
												}
											}
										}
									});
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
					
				}
			}

			@Override
			public void onError(WeiboDialogError error) {
				Toast.makeText(ReportDetailActivity.this, "认证失败!", Toast.LENGTH_LONG).show();
				Log.i("debug", "onError:" + error.getMessage() );
			}

			@Override
			public void onWeiboException(WeiboException arg0) {
				Toast.makeText(ReportDetailActivity.this, "认证失败!", Toast.LENGTH_LONG).show();
			}
		}

	/**
	 * 腾讯微博授权
	 */
	private void TXWBAccessToken() {
		String accessToken = com.tencent.weibo.sdk.android.api.util.Util
				.getSharePersistent(getApplicationContext(), "ACCESS_TOKEN");
		if (accessToken == null || "".equals(accessToken)) {
			Toast.makeText(this, "请先授权", Toast.LENGTH_SHORT).show();
			long appid = Long.valueOf(UrlConfig.tx_wb_appId);
			String app_secket = UrlConfig.tx_wb_appsecret;
			auth(appid, app_secket);
		} else {
			// isShare =false;
			if (tx_weiboAPI == null) {
				AccountModel account = new AccountModel(accessToken);
				tx_weiboAPI = new WeiboAPI(account);
			}
			UICore.eventTask(ReportDetailActivity.this,
					ReportDetailActivity.this, menu_tengxun, null, true);
		}
	}
		
		
		
		
		/**
		 * 腾讯微博授权
		 * 
		 * @param appid
		 * @param app_secket
		 */
		private void auth(final long appid, String app_secket) {
			final Context context = this.getApplicationContext();

			AuthHelper.register(this, appid, app_secket, new OnAuthListener() {

				@Override
				public void onWeiBoNotInstalled() {
					Toast.makeText(ReportDetailActivity.this, "onWeiBoNotInstalled",
							1000).show();
					Intent i = new Intent(ReportDetailActivity.this, Authorize.class);
					startActivity(i);
				}

				@Override
				public void onWeiboVersionMisMatch() {
					Toast.makeText(ReportDetailActivity.this, "onWeiboVersionMisMatch",
							1000).show();
					Intent i = new Intent(ReportDetailActivity.this, Authorize.class);
					startActivity(i);
				}

				@Override
				public void onAuthFail(int result, String err) {
					Toast.makeText(ReportDetailActivity.this, "result : " + result, 1000)
							.show();
				}

				@Override
				public void onAuthPassed(String name, WeiboToken token) {
					Toast.makeText(ReportDetailActivity.this, "passed", 1000).show();
					//
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "ACCESS_TOKEN",
									token.accessToken);
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "EXPIRES_IN",
									String.valueOf(token.expiresIn));
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "OPEN_ID", token.openID);
					// Util.saveSharePersistent(context, "OPEN_KEY", token.omasKey);
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "REFRESH_TOKEN", "");
					// Util.saveSharePersistent(context, "NAME", name);
					// Util.saveSharePersistent(context, "NICK", name);
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "CLIENT_ID",
									UrlConfig.tx_wb_appId);
					com.tencent.weibo.sdk.android.api.util.Util
							.saveSharePersistent(context, "AUTHORIZETIME", String
									.valueOf(System.currentTimeMillis() / 1000l));
					if (tx_weiboAPI == null) {
						AccountModel account = new AccountModel(token.accessToken);
						tx_weiboAPI = new WeiboAPI(account);
					}
					UICore.eventTask(ReportDetailActivity.this,
							ReportDetailActivity.this, menu_tengxun, null, true);

				}
			});

			AuthHelper.auth(this, "");
		}
		
		
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.tencent.weibo.sdk.android.network.HttpCallback#onResult(java.lang
	 * .Object) 腾讯微博返回的结果
	 */
	@Override
	public void onResult(Object arg0) {
		if (arg0 != null) {
			ModelResult result = (ModelResult) arg0;
			if (result.isExpires()) {
				Toast.makeText(ReportDetailActivity.this,
						result.getError_message(), Toast.LENGTH_SHORT).show();
			} else {
				if (result.isSuccess()) {
					Log.d("debug", "发送成功");
					handler.sendEmptyMessage(menu_tengxun);
				} else {
					Toast.makeText(ReportDetailActivity.this,
							((ModelResult) arg0).getError_message(), 4000)
							.show();
				}
			}
		}
	}
	

	
	private class BaseApiListener implements IRequestListener {
        private String mScope = "all";
        private Boolean mNeedReAuth = false;

        public BaseApiListener(String scope, boolean needReAuth) {
            mScope = scope;
            mNeedReAuth = needReAuth;
        }

        @Override
        public void onComplete(final JSONObject response, Object state) {
            doComplete(response, state);
        }

        protected void doComplete(JSONObject response, Object state) {
            try {
                final int ret = response.getInt("ret");
                if (ret == 100030) {
                    if (mNeedReAuth) {
                        Runnable r = new Runnable() {
                            public void run() {
                                mTencent.reAuth(ReportDetailActivity.this, mScope, new ShareUtils.BaseUiListener());
                            }
                        };
                        ReportDetailActivity.this.runOnUiThread(r);
                    }
                } else {
                	handler.post(new Runnable() {
						
						@Override
						public void run() {
							Log.d("debug", "doComplete--==>"+ret);
							Toast.makeText(ReportDetailActivity.this, "发送成功", 4000).show();
						}
					});
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("toddtest", response.toString());
            }

        }

        @Override
        public void onIOException(final IOException e, Object state) {
            showResult("IRequestListener.onIOException:", e.getMessage());
        }

        @Override
        public void onMalformedURLException(final MalformedURLException e, Object state) {
            showResult("IRequestListener.onMalformedURLException", e.toString());
        }

        @Override
        public void onJSONException(final JSONException e, Object state) {
            showResult("IRequestListener.onJSONException:", e.getMessage());
        }

        @Override
        public void onConnectTimeoutException(ConnectTimeoutException arg0, Object arg1) {
            showResult("IRequestListener.onConnectTimeoutException:", arg0.getMessage());

        }

        @Override
        public void onSocketTimeoutException(SocketTimeoutException arg0, Object arg1) {
            showResult("IRequestListener.SocketTimeoutException:", arg0.getMessage());
        }

        @Override
        public void onUnknowException(Exception arg0, Object arg1) {
            showResult("IRequestListener.onUnknowException:", arg0.getMessage());
        }

        @Override
        public void onHttpStatusException(HttpStatusException arg0, Object arg1) {
            showResult("IRequestListener.HttpStatusException:", arg0.getMessage());
        }

        @Override
        public void onNetworkUnavailableException(NetworkUnavailableException arg0, Object arg1) {
            showResult("IRequestListener.onNetworkUnavailableException:", arg0.getMessage());
        }
    }


	



	/**
	 * qq登录
	 */
	private void onQQLogin() {
		String SCOPE = "all";
		mTencent = AccessTokenKeeper.readTXQQToken(this, mTencent);
		if (!mTencent.isSessionValid()) {
			IUiListener listener = new ShareUtils.BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					try {
						AccessTokenKeeper.keepTXQQToken(ReportDetailActivity.this,mTencent, values.getString("expires_in"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (mTencent.isSessionValid()&& mTencent.getOpenId() != null) {
						 onQQAddShare();
					}
				}
			};
			mTencent.login(this, SCOPE, listener);
		} else {
			// mTencent.logout(this);
			 onQQAddShare();
		}
	}
	
	/**
	 * 分享到QQ空间
	 */
	private void onQQAddShare() {
//		String photo_url = "http://www.zhianleida.com/safe_cards/share.jpg?key=9d387f33832511d2c13f8859352afbdf";
		Bundle parmas = new Bundle();
		parmas.putString("title", tv_reportType.getText().toString());// 必须。feeds的标题，最长36个中文字，超出部分会被截断。
		//url 是先写死的
		parmas.putString("url", share_url);//
		parmas.putString("summary", content);// 所分享的网页资源的摘要内容，或者是网页的概要描述。//
												// 最长80个中文字，超出部分会被截断。
		parmas.putString("images", reportDetailEntity.getBmiddle_pic());// 所分享的网页资源的代表性图片链接"，请以http://开头，长度限制255字符。多张图片以竖线（|）分隔，目前只有第一张图片有效，图片规格100*100为佳。
		parmas.putString("type", "4");// 分享内容的类型。 4 是图片
		parmas.putString("nswb", "1");
		mTencent.requestAsync(Constants.GRAPH_ADD_SHARE, parmas,
				Constants.HTTP_POST, new BaseApiListener("add_share", true),
				null);

	}
		
	private void showResult(final String base, final String msg) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				destroyDialog();
				Toast.makeText(ReportDetailActivity.this, base + msg,
						Toast.LENGTH_LONG).show();
			}
		});
	}

	

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// must call mTencent.onActivityResult.
		if (!mTencent.onActivityResult(requestCode, resultCode, data)) {
		}
	}

}
